<?php

/*
 * Управление рубриками новостей
 */

namespace APPS\NEWS\CONTROLLERS\ADMIN;

use T4\Exception;
use T4\FS\Uploader;
use APPS\NEWS\MODELS\Rubric;

class Rubrics extends \T4\Controller {

	public function actionDefault() {

		$rubrics = Rubric::findAll('order');
		$this->output->rubrics = $rubrics;

		$emptyRubric = new Rubric;
		$this->output->rubric = $emptyRubric;
		
	}
	
	public function actionOrder() {
		foreach ( $_POST['order'] as $id=>$order ) {
			$item = Rubric::findByPK($id);
			if ( $item ) {
				$item->order = $order;
				$item->save();
			}
		}
		$this->redirect('/admin/news/Rubrics');
	}

	public function actionSave() {

		if (!empty($_REQUEST['id']))
			$rubric = Rubric::findByPK(intval($_REQUEST['id']));
		else
			$rubric = new Rubric;

		try {

			$rubric->mergeArray($_POST);

			$uploader = new Uploader();
			$uploader->setModel($rubric);
			$uploader->setUploadPath('news/rubrics');

			$rubric->image = $uploader('image');
			
			$rubric->save();

			$this->redirect('/admin/news/Rubrics');
			
		} catch (Exception $e) {

			throw $e;
			
		}

		$this->output->rubric = $rubric;
		
	}

	public function actionEdit() {

		$rubric = Rubric::findByPK(intval($_REQUEST['id']));
		$this->output->rubric = $rubric;
		
	}

	public function actionDelete() {

		$rubric = Rubric::findByPK(intval($_REQUEST['id']));
		$rubric->delete();

		$this->redirect('/admin/news/Rubrics');
			
	}

}